package com.ioidea.ble.lock

import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock

class BleLock<T> constructor(var lock:ReentrantLock = ReentrantLock(), var condition: Condition=lock.newCondition()) {

    companion object{
        val TIME_OUT: Long =  10 * 1000
    }

    private var data: T? = null


    fun lock() {
        lock.lock()
    }

    fun unlock() {
        lock.unlock()
    }

    /**
     * 等待指定时长
     *
     * @param time 时间
     * @param unit 时间单位
     * @return 如果等待时间内得到了响应则返回true，如果超时则返回false
     * @throws InterruptedException
     */
    @Throws(InterruptedException::class)
    fun await(time: Long, unit: TimeUnit?): Boolean {
        // 1分钟等待超时
        return condition.await(time, unit)
    }

    /**
     * 默认等到500毫秒
     *
     * @return
     * @throws InterruptedException
     */
    @Throws(InterruptedException::class)
    fun await(): Boolean {
        return await(TIME_OUT, TimeUnit.MILLISECONDS)
    }

    fun awaitUninterruptibly() {
        condition.awaitUninterruptibly()
    }

    fun signal() {
        condition.signal()
    }

    fun setData(data: T) {
        this.data = data
    }

    fun getData(): T? {
        return data
    }
}